<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class ApiFormRequestBase extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }


    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
        ];
    }

    public function messages ()
    {
        return  [

        ];
    }


    /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        try {
            throw (new ValidationException($validator));
        } catch (ValidationException $exception) {
            $error = current($exception->errors())[0];
            Log::error("校验错误：",[$error]);
            $error = [
                'status' => 'failed',
                'error' => [
                    'code' => $exception->status,
                    'msg'  => $error
                ]
            ];
            $headers = [
                'Access-Control-Allow-Origin'=> '*',
                'Access-Control-Allow-Headers'=> 'Origin,No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, token',
                'Access-Control-Allow-Methods'=> 'GET, POST, PATCH, PUT, OPTIONS, DELETE',
                'Access-Control-Allow-Credentials'=> 'true',
            ];
            response()->json($error, $exception->status, $headers)->send();
            exit();
        }
    }
}
